﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Castle.MonoRail.Framework;

using MonoRailRSS.Models;

namespace MonoRailRSS.Controllers
{
    [Layout("default")]
    public class HomeController : SmartDispatcherController
    {
        private IFeedRepository _feeds = new FeedRepository();

        public void Index()
        {
            PropertyBag["time"] = DateTime.Now.ToLongTimeString();
            PropertyBag["feeds"] = _feeds.GetAll();
        }

        public void ViewFeed(string id)
        {
            var feed = _feeds.Find(f=>f.Id ==int.Parse(id));
            if (feed == null)
                Flash["error"] = "feed does not exist";
            else
            {
                PropertyBag["name"] = feed.Name;
                PropertyBag["posts"] = _feeds.GetPosts(feed);
            }
            PropertyBag["currentFeed"] = feed;
            PropertyBag["feeds"] = _feeds.GetAll();
        }

        public void AddFeed(string feedUrl)
        {
            if (!_feeds.Exists(feed => feed.FeedUrl == feedUrl))
            {
                var rssDoc = XDocument.Load(feedUrl);
                _feeds.Add(new RSSFeed(){
                    FeedUrl=feedUrl,
                    Name=rssDoc.Element("rss").Element("channel").Element("title").Value});
            }
            RedirectToAction("index");
        }
    }
}
